package panicsafe

import (
	"fmt"
	"strings"
	"time"
)

/***
 * 如果时间为空，则返回""
 */
func DateTimeString2(val time.Time) string {
	if val.IsZero() {
		return ""
	} else {
		return val.Format("2006-01-02 15:04:05")
	}
}

func NowString() string {
	return time.Now().Format("2006-01-02 15:04:05")
}

// a:0时, f(a+6):6时, (a+23):23时,
func ToHourChr(atime time.Time) string {
	h := atime.Hour()
	i := int(rune('a'))
	rval := string(rune(i + h))
	return rval
}

// A:0时, F(A+6):6时, (A+23):23时,
func ToHourChrUpcase(atime time.Time) string {
	h := atime.Hour()
	i := int(rune('A'))
	rval := string(rune(i + h))
	return rval
}

func DayOfYear(atime time.Time) string {
	v := atime.YearDay()
	return fmt.Sprintf("%.3d", v)
}

func Split2Str(s, sep string) (s1, s2 string) {
	if len(s) == 0 {
		return
	}
	idx := strings.Index(s, sep)
	if idx == -1 {
		return s, ""
	}
	return s[:idx], s[idx+len(sep):]
}

func GetDateTimeKeyValue(key string, _t time.Time) (v string, ok bool) {
	s1, s2 := Split2Str(key, ":")
	if len(s1) > 0 {
		if s1 == "u" || s1 == "utc" {
			_t = _t.UTC()
			key = s2
		}
	}
	if key == "yyyy" {
		return _t.Format("2006"), true
	} else if key == "yy" {
		return _t.Format("06"), true
	} else if key == "mm" {
		return _t.Format("01"), true
	} else if key == "dd" {
		return _t.Format("02"), true
	} else if key == "yyyymmdd" {
		return _t.Format("20060602"), true
	} else if key == "hh" {
		return _t.Format("15"), true
	} else if key == "mi" {
		return _t.Format("04"), true
	} else if key == "ss" {
		return _t.Format("05"), true
	} else if key == "doy" {
		return DayOfYear(_t), true
	} else if key == "HC" {
		return ToHourChrUpcase(_t), true
	} else if key == "hc" {
		return ToHourChr(_t), true
	} else if key == "qu" || key == "m15" {
		mi := _t.Minute()
		qua := mi / 15 * 15
		strQua := fmt.Sprintf("%.2d", qua)
		return strQua, true
	} else if key == "m5" {
		mi := _t.Minute()
		v0 := mi / 5 * 5
		str := fmt.Sprintf("%.2d", v0)
		return str, true
	} else if key == "m10" {
		mi := _t.Minute()
		v0 := mi / 10 * 10
		str := fmt.Sprintf("%.2d", v0)
		return str, true
	} else if key == "timeid" {
		return _t.Format("150405"), true
	}
	return "", false
}
